package gaoji;

import java.util.concurrent.locks.ReentrantLock;

/**
 * lock锁一般使用try语句
 */
public class TestLock {
    public static void main(String[] args) {
        MyLock myLock = new MyLock();
        new Thread(myLock).start();
        new Thread(myLock).start();
        new Thread(myLock).start();
    }
}

class MyLock implements Runnable {
    //Lock锁
    private final ReentrantLock lock = new ReentrantLock();
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            try {
                //资源操作前上锁
                lock.lock();
                if (ticketNums > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //lock.lock();//资源不够多线程分配，但却能进入，等待其他线程消耗完释放锁再使用就会造成资源为负
                    System.out.println(ticketNums--);
                } else {
                    break;
                }
            } finally {
                lock.unlock();
            }

        }
    }
}